package com.cw.jeeyt.controller.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumDataJavaType;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.enums.EnumYn;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.system.SystemColumnInfoBo;
import com.cw.jeeyt.service.bo.system.SystemTableInfoBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.system.SystemColumnInfoService;
import com.cw.jeeyt.service.intf.system.SystemTableInfoService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 表模型信息控制类
 * @author chenw
* @version 1.0.0
 */
@Controller
@RequestMapping("/systemTableInfo")
public class SystemTableInfoController extends BaseController {
    @Autowired
    @Lazy
    private SystemTableInfoService systemTableInfoService;
    @Autowired
    @Lazy
    private SystemColumnInfoService systemColumnInfoService;

    /**
     * 跳转到列表查询页面
     *
     * @param systemTableInfoBo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query(SystemTableInfoBo systemTableInfoBo) throws Exception {
        ModelAndView mv = new ModelAndView("system/systemTableInfo_index");
        mv.addObject("moduleId", systemTableInfoBo.getModuleId());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSystemTableInfo")
    public ResultData listSystemTableInfo(@RequestBody DataTable dataTable, String moduleId) throws Exception {

        SystemTableInfoBo systemTableInfoBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SystemTableInfoBo.class);
        if (systemTableInfoBo == null) {
            systemTableInfoBo = new SystemTableInfoBo();
        }
        systemTableInfoBo.setModuleId(moduleId);
        PageInfo<SystemTableInfoBo> pageInfo = systemTableInfoService.queryByPage(systemTableInfoBo,
            dataTable.getStart(), dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView toForm(String id, String moduleId, String operation)
    throws Exception {
        ModelAndView mv = new ModelAndView("system/systemTableInfo_form");
        SystemTableInfoBo systemTableInfoBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            systemTableInfoBo = new SystemTableInfoBo();
            systemTableInfoBo.setModuleId(moduleId);
        } else {
            systemTableInfoBo = systemTableInfoService.getSystemTableInfoById(id);
        }
        mv.addObject("systemTableInfo", systemTableInfoBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存数据
     *
     * @param systemTableInfoBo
     * @param operation add新增  edit修改 view查看
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveSystemTableInfo", method = RequestMethod.POST)
    public JsonResultDto saveSystemTableInfo(SystemTableInfoBo systemTableInfoBo, String operation) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                systemTableInfoService.insertSystemTableInfo(systemTableInfoBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                systemTableInfoService.updateSystemTableInfo(systemTableInfoBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

        }
        jsonResultDto.setOperation(operation);
        return jsonResultDto;
    }

    /**
     * 删除表模型信息
     *
     * @param systemTableInfoBo
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto deleteSystemTableInfo(SystemTableInfoBo systemTableInfoBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemTableInfoService.deleteSystemTableInfo(systemTableInfoBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 配置页面元素
     *
     * @param tableId
     * @return
     * @throws Exception
     */
    @RequestMapping("/configPageColumnInfo")
    public ModelAndView configPageColumnInfo(String tableId) throws Exception {
        ModelAndView mv = new ModelAndView("system/systemTableInfo_configColumn");
        SystemTableInfoBo systemTableInfo = systemTableInfoService.getSystemTableInfoById(tableId);
        List<SystemColumnInfoBo> systemColumnInfoList = systemColumnInfoService.queryColumnInfoListByTableId(tableId);
        //根据字段的数据类型先初始化一部分值
        if (systemColumnInfoList != null && !systemColumnInfoList.isEmpty()) {
            for (SystemColumnInfoBo sci : systemColumnInfoList) {
                String columnType = sci.getColumnType();
                if (EnumDataJavaType.DATE.getCode()
                    .equals(columnType)) {
                    sci.setIsDate(EnumYn.Y.getCode());
                    sci.setIsAmt(EnumYn.N.getCode());
                    sci.setIsRate(EnumYn.N.getCode());
                    sci.setIsNumber(EnumYn.N.getCode());
                } else if (EnumDataJavaType.INTEGER.getCode()
                    .equals(columnType) || EnumDataJavaType.LONG.getCode()
                    .equals(columnType)) {
                    sci.setIsNumber(EnumYn.Y.getCode());
                    sci.setIsDate(EnumYn.N.getCode());
                    sci.setIsAmt(EnumYn.N.getCode());
                    sci.setIsRate(EnumYn.N.getCode());
                } else if (EnumDataJavaType.BIGDECIMAL.getCode()
                    .equals(columnType)) {
                    sci.setIsNumber(EnumYn.N.getCode());
                    sci.setIsDate(EnumYn.N.getCode());
                    sci.setIsAmt(EnumYn.Y.getCode());
                    sci.setIsRate(EnumYn.N.getCode());
                }
            }
        }

        mv.addObject("systemTableInfo", systemTableInfo);
        mv.addObject("systemColumnInfoList", systemColumnInfoList);
        return mv;
    }

    /**
     * 自动生成代码
     *
     * @param tableIds 表id集合
     * @param moduleId 模块id
     * @param generateType 生成代码方式
     */
    @RequestMapping(value = "/generateCode")
    public void generateCode(HttpServletRequest request, HttpServletResponse response, String tableIds, String moduleId,
        String generateType) {
        try {
            systemTableInfoService.generateCode(tableIds, moduleId, generateType, request, response);
        } catch (Exception e) {
            logger.error("自动生成代码失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 自动生成代码
     *
     * @param moduleId 模块id
     */
    @RequestMapping(value = "/clearDatabaseInfo")
    @ResponseBody
    public JsonResultDto clearDatabaseInfo(String moduleId) {
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemTableInfoService.clearDatabaseInfo(moduleId);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 自动生成代码
     *
     * @param moduleId 模块id
     * @param generateType 生成代码方式
     * @throws Exception
     */
    @RequestMapping(value = "/generateAllCode")
    public void generateAllCode(HttpServletRequest request, HttpServletResponse response, String moduleId,
        String generateType) {
        try {
            systemTableInfoService.generateAllCode(moduleId, generateType, request, response);
        } catch (Exception e) {
            logger.error("自动生成所有代码失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 同步数据库表信息、字段信息到表模型信息、数据条目信息、表模型字段信息
     *
     * @param tableIds 表id集合
     * @param moduleId 模块id
     * @throws Exception
     */
    @RequestMapping(value = "/importDatabaseTableInfo")
    @ResponseBody
    public JsonResultDto importDatabaseTableInfo(String tableIds, String moduleId) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemTableInfoService.importDatabaseTableInfo(tableIds, moduleId);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("同步数据库信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("同步数据库信息失败：" + e.getMessage());
        }
        return jsonResultDto;
    }
}
